<?php
/**
 * Project Model Class File
 *
 * @package
 * @author Joachim Werner <joachim.werner@diggin-data.de>
 */

/**
 * This is the model class for table "project".
 *
 * The followings are the available columns in table 'project':
 * @property integer $id
 * @property string $name
 * @property string $description
 *
 * @package
 * @author Joachim Werner <joachim.werner@diggin-data.de>
 * @version $Rev: 6 $
 */
class Project extends MyModel
{
    // {{{ *** Members ***

    /**
     * List of fields composing the record name (separated by ;)
     * @var string
     */
    var $nameFields = "name;id";

    /**
     * Name format string (e.g. '{1} (#{2})' 
     * @var string
     */
    var $nameFormat = "{1} (#{2})";
    
    /**
     * Does this model use record revisions?
     * @var bool
     */
    var $usesRevision   = false;

    /**
     * Revision number of current record
     * @var int
     */
    var $recordRevision;

    /**
     * Does this model use logging?
     * @var bool
     */
    var $usesLog        = false;

    public $newMembersEmails;

    // }}} 
    // {{{ *** Methods ***
    // {{{ model
    /**
     * Returns the static model of the specified AR class.
     * @return Project the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    } // }}} 
    // {{{ tableName
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'project';
    } // }}} 
    // {{{ rules
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name', 'required'),
            array('name', 'length', 'max'=>255),
            array('isPublic','boolean'),
            array('description', 'safe'),
            array('newMembersEmails','safe','on'=>'update'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, description, isPublic', 'safe', 'on'=>'search'),
        );
    } // }}} 
    // {{{ afterSave
    /**
     * This is invoked after the record is saved.
     *
     * After saving a project, selected members can be deleted.
     * New members will be added.
     */
    protected function afterSave()
    {
        parent::afterSave();
        // Remove Members?
        if(isset($_POST['RemoveMembers'])) {
            $memberIDs = join(',',$_POST['RemoveMembers']);
            $sql = "DELETE FROM UserProject WHERE userId IN ($memberIDs)";
            Yii::app()->db->createCommand($sql)->execute();
        }
        // Add Members?
        if($this->newMembersEmails!=='') {
            $this->newMembersEmails = str_replace("\r\n", "\n", $this->newMembersEmails);
            $userEmails = preg_split('/\s*[,|\n]\s*/',trim($this->newMembersEmails),-1,PREG_SPLIT_NO_EMPTY);
            foreach($userEmails as $userEmail) {
                if(!is_null($user = User::model()->findByAttributes(array('email'=>trim($userEmail))))) {
                    $sql = "INSERT INTO UserProject (userId, projectId, isApproved) VALUES (:userId, :projectId, 1)";
                    Yii::app()->db->createCommand($sql)->execute(array(':userId'=>$user->id,':projectId'=>$this->id));
                }
            }
        }
    } // }}} 
    // {{{ relations
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'milestones'    => array(self::HAS_MANY,'Milestone','projectId'),
            'issues'        => array(self::HAS_MANY,'Issue','projectId'),
            'createdBy'     => array(self::BELONGS_TO,'User','userIdCreated'),
            'updatedBy'     => array(self::BELONGS_TO,'User','userIdUpdated'),
            'members'       => array(self::MANY_MANY, 'User','UserProject(userId, projectId)'),
        );
    } // }}} 
    // {{{ behaviors
    public function behaviors(){
        return array(
            'Timestamp2Behavior' => array(
                'class' => 'application.components.behaviors.TimestampBehavior',
            )
        );
    } // }}} 
    // {{{ attributeLabels
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('site','ID'),
            'name' => Yii::t('site','Name'),
            'description' => Yii::t('site','Description'),
            'isPublic' => Yii::t('site','Visible for Public'),
            'tsCreated' => Yii::t('site','Created'),
            'userIdCreated' => Yii::t('site','Created By'),
            'tsUpdated' => Yii::t('site','Updated'),
            'userIdUpdated' => Yii::t('site','Updated By'),
        );
    } // }}} 
    // {{{ search
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('description',$this->description,true);
        if(Yii::app()->user->isGuest)
            $criteria->addCondition('isPublic=1');
        else
            $criteria->compare('isPublic',$this->isPublic);
        return new CActiveDataProvider(get_class($this), array('criteria'=>$criteria));
    } // }}} 
    // {{{ getSelectOptions
    /**
     * Returns an array of all project names, indexed by id's
     * 
     * @access public
     * @return mixed
     */
    public function getSelectOptions()
    {
        $models = $this->findAll(array('order'=>'name'));
        $result = array();
        foreach($models as $model)
            $result[$model->id] = $model->recordName;
        return $result;
    } // }}} 
    // {{{ getMembersDataProviderDataProvider
    /**
     * Returns a CArrayDataProvider with project's members
     * 
     * @access public
     * @return mixed
     */
    public function getMembersDataProvider()
    {
        $sql = "SELECT u.id AS memberId, CONCAT(u.firstName,' ',u.lastName) AS fullname, u.username, u.email, up.projectId, p.userIdCreated AS ownerId "
            ."FROM User u "
            ."LEFT JOIN UserProject up ON u.id=up.userId "
            ."LEFT JOIN Project p ON up.projectId=p.id "
            ."WHERE up.projectId=:projectId "
            ."ORDER BY fullname";
        $params = array(':projectId' => $this->id);
        $members=Yii::app()->db->createCommand($sql)->queryAll(true, $params);
        // or using: $rawData=User::model()->findAll();
        $dataProvider=new CArrayDataProvider($members, array(
            'id'=>'memberId',
        ));
        return $dataProvider;
    } // }}} 
    // }}} 
}

/* vim: set ai sw=4 sts=4 et fdm=marker fdc=4 */ 
?>
